/*
 * Copyright 2008 Yubico
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 *
 * You may obtain a copy of the License at 
 *   http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 *
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 *
 */
package com.yubico.wsapi;

import java.util.Date;

import org.apache.log4j.Logger;

/**
 * A Client is a Yubikey issuer that issues Yubikeys and call this validation
 * server to verify OTPs generated by Yubikeys it issued. 
 * 
 * If you run your own web site and you issue Yubikeys to your users from there, 
 * you need only 1 Client in the database, that's your company itself.
 *
 */
public class Client
{
  static Logger log = Logger.getLogger (Client.class);

  private Secret secret;

  private boolean active;

  private Perms perms;

  private Date created;

  private String email;

  public Client (Date created, boolean active, String email, Secret secret,
		 Perms perms)
  {
    this.created = created;
    this.active = active;
    this.email = email;
    this.secret = secret;
    this.perms = perms;
  }

  Date getCreated ()
  {
    return created;
  }

  boolean getActive ()
  {
    return active;
  }

  String getEmail ()
  {
    return email;
  }

  Secret getSecret ()
  {
    return secret;
  }

  Perms getPerms ()
  {
    return perms;
  }

  public Secret createSecret (String email)
  {
    String ts = "" + new java.util.Date ().getTime ();
    return Secret.fromBase64 (Crypto.sign (email + ts, secret));
  }

  static Client lookup (String id)
  {
    Database db = Database.getDefault ();
    return db.getClient (id);
  }

	/**
	 * Checks whether the request is allowed by this client.
	 */
  public boolean checkPerms (Request request)
  {
    return perms.check (request);
  }

  public String toString ()
  {
    return "[Client created=" + created + ", email=" + email + ", secret="
      + secret + ", perms=" + perms + "]";
  }
}
